import {computed, designComponent, onMounted, reactive} from "plain-ui-composition";
import {$$message, PlIcon, PlInput} from "plain-ui";
import {copyToClipboard} from 'plain-utils/dom/copyToClipboard'
import './IconSearch.scss'

export const IconSearch = designComponent({
    name: 'icon-search',
    setup() {

        const state = reactive({
            searchValue: null as null | string,
            targetSearchValue: null as null | string,
            icons: [] as string[],
        })
        const targetIcons = computed(() => {
            if (!state.targetSearchValue) {return state.icons}
            return state.icons.filter(icon => `el-icon-${icon}`.indexOf(state.targetSearchValue!) > -1)
        })
        const handler = {
            onEnter: () => {
                state.targetSearchValue = state.searchValue
            },
            onClickIcon: (icon: string) => {
                copyToClipboard(icon, () => $$message(`已经复制到剪切板:${icon}`))
            }
        }

        onMounted(async () => {
            state.icons = (await import('plain-ui/src/packages/PlIcon/icons/index.json') as any as { default: string[] }).default
        })

        return {
            render: () => (
                <div class="icon-search">
                    <h2>搜索图标</h2>
                    <div class="icon-search-input">
                        <PlInput
                            v-model={state.searchValue}
                            suffixIcon="el-icon-search"
                            size="large"
                            shape="round"
                            width="500"
                            onEnter={handler.onEnter}
                            onClickSuffixIcon={handler.onEnter}
                        />
                    </div>
                    <div class="demo-icon-list">
                        <ul class="icon-list">
                            {targetIcons.value.map(icon => <li key={icon} onClick={() => handler.onClickIcon(icon)}>
                                <p>
                                    <PlIcon icon={icon}/>
                                </p>
                                <div>
                                    {icon}
                                </div>
                            </li>)}
                        </ul>
                    </div>
                </div>
            )
        }
    },
})
